from aip import AipImageClassify
import tkinter as tk
from tkinter import filedialog, messagebox
import os
import cv2 as cv

def select_image():
    filepath = filedialog.askopenfilename(
        title="选择图片",
        filetypes=[("图片文件", "*.jpg;*.jpeg;*.png")]
    )
    if filepath:
        analyze_image(filepath)

class Camera:
    def __init__(self):
        cv.namedWindow("Camera")
        self.cam = cv.VideoCapture(0)
        while True:
            ret, self.frame = self.cam.read()
            if ret:
                cv.imshow('Eraser', self.frame)
            if ord('t') == cv.waitKey(1000//60):
                self.save_photo()
                break

    def save_photo(self):
        cv.imwrite('temp.jpg', self.frame)
    
    def __del__(self):
        self.cam.release()
        cv.destroyAllWindows()

def take_photo():
    C = Camera()
    analyze_image('temp.jpg')

def analyze_image(path):
    try:
        APP_ID, API_KEY, SECRET_KEY = open("key.txt").read().split()
        client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)
        
        img = open(path, "rb").read()
        result = client.advancedGeneral(img)
        
        # 解析结果
        items = [f"{i+1}. {item['keyword']} (置信度：{item['score']:.2%})" 
                for i, item in enumerate(result['result'])]
        
        # 显示结果
        result_text = "识别结果：\n" + "\n".join(items)
        messagebox.showinfo("分析完成", result_text)
        
    except Exception as e:
        messagebox.showerror("出错", f"识别失败：{str(e)}")

# 创建图形界面
root = tk.Tk()
root.title("图片识别工具 v1.0")
root.geometry("400x300")  # 新增设置窗口尺寸

frame = tk.Frame(root, padx=20, pady=20)
frame.pack()

tk.Label(frame, text="图片识别工具", font=("微软雅黑", 16)).pack(pady=10)
tk.Button(frame, 
         text="选择图片", 
         command=select_image,
         width=20,
         height=2).pack(pady=10)
tk.Button(frame, 
         text="拍照识别", 
         command=take_photo,
         width=20,
         height=2).pack(pady=10)

root.mainloop()